package controller

import (
	"comic/internal/logic/comic"
	l "comic/internal/logic/comic"
	"comic/internal/logic/navigate"
	"comic/internal/pb"
	"common"
	"common/auth"
	"common/zapx"
	"context"
	"models/dal/query"
	"time"

	"go.uber.org/zap"
)

type ComicServer struct {
	pb.UnimplementedComicServer
	logic l.ComicLogic
}

// NewComicService 创建新的服务
func NewComicService() *ComicServer {
	return &ComicServer{
		logic: l.NewComicLogic(),
	}
}

func (cs *ComicServer) ComicList(ctx context.Context, req *pb.ComicListRequest) (*pb.ComicListResponse, error) {
	cs.logic.SetPage(req.Page)
	cs.logic.SetPerPage(req.PerPage)
	return &pb.ComicListResponse{
		List: cs.logic.GetList(req.Title, req.NavigateId),
		Page: cs.logic.GetPageInfo(),
	}, nil
}

func (cs *ComicServer) ChapterList(ctx context.Context, req *pb.ChapterListRequest) (*pb.ChapterListResponse, error) {
	cs.logic.SetPage(req.Page)
	cs.logic.SetPerPage(req.PerPage)
	return &pb.ChapterListResponse{
		List: cs.logic.GetChapterListByComicId(req.ComicId),
		Page: cs.logic.GetPageInfo(),
	}, nil
}

func (cs *ComicServer) Resource(ctx context.Context, req *pb.ResourceRequest) (*pb.ResourceResponse, error) {
	images, err := comic.GetResourceByChapterId(ctx, req.ChapterId)
	if err != nil {
		return nil, err
	}
	return &pb.ResourceResponse{
		Image: images,
	}, nil
}

func (cs *ComicServer) ComicDetail(ctx context.Context, req *pb.ComicDetailRequest) (*pb.ComicDetailResponse, error) {
	ret, err := cs.logic.GetComicDetail(ctx, int32(req.ComicId))
	if err != nil {
		return nil, err
	}
	return &pb.ComicDetailResponse{
		ComicInfo: ret,
	}, nil
}

func (cs *ComicServer) GetHotSearchList(ctx context.Context, req *pb.GetHotSearchListRequest) (*pb.GetHotSearchListResponse, error) {
	ctx, cancel := common.WithTimeoutContext(time.Second * 2)
	defer cancel()
	list, err := query.Q.FaHotSearch.WithContext(ctx).Limit(int(req.Limit)).Order(query.Q.FaHotSearch.Num.Desc()).Find()
	if err != nil {
		zapx.Logger.Error("查询热门搜索失败", zap.Error(err))
	}
	var l []string
	for _, search := range list {
		l = append(l, search.Content)
	}
	return &pb.GetHotSearchListResponse{
		Name: l,
	}, nil
}

func (cs *ComicServer) GetNavigateList(ctx context.Context, req *pb.GetNavigateListRequest) (*pb.GetNavigateListResponse, error) {
	res := &pb.GetNavigateListResponse{NavigateL: make([]*pb.NavigateLEntity, 0)}
	for _, item := range navigate.GetNavigateList() {
		res.NavigateL = append(res.NavigateL, &pb.NavigateLEntity{
			Id:    int64(item.ID),
			Title: item.Title,
		})
	}
	return res, nil
}

func (cs *ComicServer) GetChapterDetail(ctx context.Context, req *pb.GetChapterDetailRequest) (*pb.GetChapterDetailResponse, error) {
	return comic.ChapterDetail(ctx, req.ChapterId)
}

func (cs *ComicServer) Find(ctx context.Context, req *pb.FindRequest) (*pb.FindResponse, error) {
	if err := cs.logic.Find(auth.NewAuthObjectByGrpc(ctx), req.Title, req.Link); err != nil {
		return nil, err
	}
	return &pb.FindResponse{}, nil
}
